import glob
import Image
import optparse
import os

parser = optparse.OptionParser()
parser.add_option('--input_dir', dest='input_dir', help='Image input directory.')
parser.add_option('--output_dir', dest='output_dir', help='Image output directory.')
parser.add_option('--size', dest='size', help='Image size.', type='int')
options, args = parser.parse_args()

if not options.input_dir:
  parser.error('Missing --input_dir.')
if not options.output_dir:
  parser.error('Missing --output_dir.')
if not options.size:
  parser.error('Missing --size.')

if not os.path.isdir(options.input_dir):
  parser.error('%s does not exist.' % options.input_dir)
if not os.path.isdir(options.output_dir):
  parser.error('%s does not exist.' % options.output_dir)

image_paths = glob.glob(os.path.join(options.input_dir, '*.jpg'))
for image_path in image_paths:
  print 'Opening %s' % image_path
  image = Image.open(image_path)
  width, height = image.size

  if width > height:
    height = height * options.size / width
    width = options.size
  else:
    width = width * options.size / height
    height = options.size

  print 'Resizing'
  image = image.resize((width, height), Image.ANTIALIAS)

  output_path = os.path.join(options.output_dir, os.path.basename(image_path))
  print 'Saving as %s' % output_path
  image.save(output_path)
